package com.ddxz.hospital.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/9/23
 */

public class ArrayHandler extends BaseTypeHandler<Object[]> {
    private static final String TYPE_CHAR = "text";
    private static final String TYPE_INT = "int4";
    private static final String TYPE_FLOAT = "float4";

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object[] objects, JdbcType jdbcType) throws SQLException {
        String typeName = "";
        if (objects instanceof Integer[]) {
            typeName = "int4";
        } else if (objects instanceof String[]) {
            typeName = "text";
        } else if (objects instanceof Float[]) {
            typeName = "float4";
        }

        Connection conn = preparedStatement.getConnection();
        Array array = conn.createArrayOf(typeName, objects);
        preparedStatement.setArray(i, array);
    }

    @Override
    public Object[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return this.getArray(resultSet.getArray(s));
    }

    private Object[] getArray(Array array) {
        if (null == array) {
            return null;
        } else {
            try {
                return (Object[])((Object[])array.getArray());
            } catch (SQLException var3) {
                var3.printStackTrace();
                return null;
            }
        }
    }

    @Override
    public Object[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return this.getArray(resultSet.getArray(i));
    }

    @Override
    public Object[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return this.getArray(callableStatement.getArray(i));
    }
}
